<?php

namespace app\admin\controller;

use app\common\controller\Backend;

use Exception;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Banc extends Backend
{

    /**
     * Banc模型对象
     * @var \app\admin\model\Banc
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Banc;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['line','driver'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('line')->visible(['line_name']);
				$row->getRelation('driver')->visible(['driver_name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function add()
    {
        if (false === $this->request->isPost()) {
            $this->assign('line_id', $this->request->param("line_id"));
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            
            $driver_id = $params['driver_id'];
            $driver_data = db('driver')->where('id',$driver_id)->field('car_seat_num')->find();
            empty($driver_data) && exception('没有找到司机信息');
            $params['ticket_num'] = $driver_data['car_seat_num'];

            $distance_data = $this->getDistance($params['line_id']);
            $params['distance'] = $distance_data['distance'];
            $params['distance_time'] = $distance_data['distance_time'];

            $result = $this->model->allowField(true)->save($params);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            
            $driver_id = $params['driver_id'];
            $driver_data = db('driver')->where('id',$driver_id)->field('car_seat_num')->find();
            empty($driver_data) && exception('没有找到司机信息');
            $params['ticket_num'] = $driver_data['car_seat_num'];
            
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function getDistance($line_id)
    {
        $line = db('line')->where('id',$line_id)->field('distance,distance_time')->find();
        if($line['distance'] && $line['distance_time']){
            return $line;
        }
        $line_station = db('line_station')
            ->where(['line_id'=>$line_id])->field('id,station_name,coordinate_lat,coordinate_lng')
            ->order('weigh desc')
            ->select();
        $start_station = $line_station[0];
        $start_coordinate = round($start_station['coordinate_lng'], 6) .','. round($start_station['coordinate_lat'], 6);
        $end_station = $line_station[count($line_station)-1];
        $end_coordinate = round($end_station['coordinate_lng'], 6) .','. round($end_station['coordinate_lat'], 6);

        $url = "https://restapi.amap.com/v5/direction/driving";
        $params = [
            'origin' => $start_coordinate,  //起点
            'destination' => $end_coordinate,  //终点
            'key' => '8f5332e89d81f800bf8c2e2ffe1c08dc',
        ];
        $ret = $this->curl($url,$params);
        $ret = json_decode($ret,true);
        $distance = @$ret['route']['paths'][0]['distance'];
        $distance || exception('获取距离失败');

        $distance = $distance / 1000; //公里
        $hour = round($distance / 80, 2); //80公里的时速
        if($hour>1){
            $shi = (int)$hour;
            $fen = $hour - $shi;
            $distance_fen = round($fen * 60);
            $distance_time = $shi."小时".$distance_fen."分钟";
        }elseif($hour==1){
            $distance_time = '1小时';
        }else{
            $distance_fen = round($hour * 60);
            $distance_time = $distance_fen.'分钟';
        }

        $ret_data = compact('distance','distance_time');
        db('line')->where('id',$line_id)->update($ret_data);

        return $ret_data;
    }

    function curl($url, $data = [])
    {
        // 处理get数据
        if (!empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书和hosts
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }


    //获取上车点
    public function getStartStation()
    {
        $line_id = I('post.id');

        $list = db('line_station')->where(['line_id'=>$line_id,'is_shang'=>1])->order('weigh desc')->field('station_name,"" as station_time')->select();
        $this->success('Success','',json_encode($list,JSON_UNESCAPED_UNICODE));
    }

}
